package com.gdk.ksoft.ui.customers;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.entry.tables.CustomerAreaTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.gdk.ksoft.assembly.utils.extensions.StringUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.List;

/**
 * 客户信息编辑
 */
public class CustomerEditActivity extends Activity {

    @ViewInject(R.id.pcustomerEdit_etCustomerName)private EditText etCustomerName;//客户名称
    @ViewInject(R.id.pcustomerEdit_etContractor)private EditText etContractor;//客户联系人
    @ViewInject(R.id.pcustomerEdit_etConnectity)private EditText etConnectity;//客户联系人电话
    @ViewInject(R.id.pcustomerEdit_etDeliverPerson)private EditText etDeliverPerson;//收货人
    @ViewInject(R.id.pcustomerEdit_etDeliverPhone)private EditText etDeliverPhone;//收货人电话
    @ViewInject(R.id.pcustomerEdit_etDeliverAddress)private EditText etDeliverAddr;//收货人地址
    @ViewInject(R.id.pcustomerEdit_etAddressAbbr)private EditText etDeliverAbbr;//收货人地址简称
    @ViewInject(R.id.pcustomerEdit_txtAddrArea)private TextView txtAddrArea;//所在地区
    @ViewInject(R.id.pcustomerEdit_txtCustomerType)private TextView txtCustomerType;//客户类型

    private DeliverGoodsTable deliverGoods = null;//客户收货地址对象
    private CustomerTable customer = null;//客户信息对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_edit);
        ViewUtils.inject(this);
        Intent intent = getIntent();
        if(intent!=null){
            int kh_id = intent.getIntExtra("customerId",0);
            int shdz_id = intent.getIntExtra("addressId",0);
            initInformation(this,kh_id,shdz_id);//初始化客户信息参数对象
        }
    }

    @OnClick(value = {R.id.pcustomerEdit_txtSubmit})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.pcustomerEdit_txtSubmit://保存客户信息
                if (!checkArguments()) return;//检测保存参数
                executeSaveTask(this);//执行数据保存业务
                break;
            default:
                break;
        }
    }

    /**
     * 执行数据保存业务
     */
    public void executeSaveTask(final Context context){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            private String errMessage = null;
            private Intent data = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在保存数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    data = saveCustomerInformation();
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage != null||data == null){
                    Toast.makeText(context,"保存数据失败!请检查输入的数据!",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(context,"保存数据成功!",Toast.LENGTH_SHORT).show();
                ((Activity)context).setResult(Activity.RESULT_OK,data);
                ((Activity)context).finish();
                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            }
        }.execute();
    }

    /**
     * 保存客户信息
     */
    public Intent saveCustomerInformation(){
        boolean isSuccessful = true;
        DbUtils dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        SQLiteDatabase database = dbUtils.getDatabase();
            try {
                database.beginTransaction();
                customer.mc = etCustomerName.getText().toString();
                customer.lxr = etContractor.getText().toString();
                customer.dh = etConnectity.getText().toString();
                customer.state = 2;//修改的客户
                customer.djbz = 0;//修改单机标识
                customer.kjj = StringUtils.getFirstLetterString(customer.mc);
                dbUtils.update(customer, "mc", "lxr", "dh","kjj","state","djbz");
                deliverGoods.shdh = etDeliverPhone.getText().toString();
                deliverGoods.shr = etDeliverPerson.getText().toString();
                deliverGoods.shdz = etDeliverAddr.getText().toString();
                deliverGoods.djbz = 0;//修改单机标识
                dbUtils.update(deliverGoods, "shdh", "shr", "shdz","khlx","jc","djbz");
                database.setTransactionSuccessful();
            }catch (Exception e){
                e.printStackTrace();
                isSuccessful = false;
            }
        database.endTransaction();
        if(isSuccessful){//如果操作成功，则返回数据
            Intent data = new Intent();
            data.putExtra("mc",customer.mc);
            data.putExtra("lxr",customer.lxr);
            data.putExtra("dh",customer.dh);
            data.putExtra("shdh",deliverGoods.shdh);
            data.putExtra("shr",deliverGoods.shr);
            data.putExtra("shdz",deliverGoods.shdz);
            return data;
        }
        return null;
    }

    /**
     * 初始化客户信息参数对象
     * @param kh_id
     * @param shdz_id
     */
    public void initInformation(final Context context,final int kh_id,final int shdz_id){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            private String errMessage = null;
            //客户类型数组
            private String[] ctypeArr = null;
            private int[] intCtypeArr = null;
            //客户地区数组
            private String[] careaArr = null;
            private int[] intCareaArr = null;

            private String currTypeName = "";
            private String currAreaName = "";
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在初始化...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    DbUtils dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
                    deliverGoods = dbUtils.findFirst(Selector.from(DeliverGoodsTable.class).where("id","=",shdz_id));
                    customer = dbUtils.findFirst(Selector.from(CustomerTable.class).where("id","=",kh_id));
                    if(deliverGoods!=null && customer!=null) initDropDownlistData(dbUtils);//初始化下拉列表参数
                }catch (Exception e){
                    e.printStackTrace();
                    errMessage = e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(deliverGoods!=null && customer!=null){
                    dealDropDownlistResult();//处理下拉列表查询结果
                    etCustomerName.setText(customer.mc);
                    etContractor.setText(customer.lxr);
                    etConnectity.setText(customer.dh);
                    etDeliverPerson.setText(deliverGoods.shr);
                    etDeliverPhone.setText(deliverGoods.shdh);
                    etDeliverAddr.setText(deliverGoods.shdz);
                    etDeliverAbbr.setText(deliverGoods.jc);
                    return;
                }
                Toast.makeText(context,"初始化失败!原因："+errMessage,Toast.LENGTH_SHORT).show();
                goBack();//关闭当前页面
            }

            /**
             * 初始化下拉列表参数
             */
            public void initDropDownlistData(DbUtils dbUtils)throws Exception{
                List<CustomerTypeTable> ctypelist = dbUtils.findAll(CustomerTypeTable.class);
                if (ctypelist != null && ctypelist.size() > 0) {
                    ctypeArr = new String[ctypelist.size()];
                    intCtypeArr = new int[ctypeArr.length];
                    for (int i = 0; i < ctypelist.size(); i++) {
                        CustomerTypeTable item = ctypelist.get(i);
                        ctypeArr[i] = item.khlx;
                        intCtypeArr[i] = item.id;
                        if(deliverGoods.khlx == item.id)
                            currTypeName = item.khlx;
                    }
                }
                List<CustomerAreaTable> carealist = dbUtils.findAll(CustomerAreaTable.class);
                if (carealist != null && carealist.size() > 0) {
                    careaArr = new String[carealist.size()];
                    intCareaArr = new int[careaArr.length];
                    for (int i = 0; i < carealist.size(); i++) {
                        CustomerAreaTable item = carealist.get(i);
                        careaArr[i] = item.mc;
                        intCareaArr[i] = item.id;
                        if(deliverGoods.dq_id == item.id)
                            currAreaName = item.mc;
                    }
                }
            }

            /**
             * 处理下拉列表查询结果
             */
            public void dealDropDownlistResult(){
                if(ctypeArr!=null && ctypeArr.length>0) {
                    txtCustomerType.setText(currTypeName);
                    txtCustomerType.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new AlertDialog.Builder(context).setItems(ctypeArr, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    txtCustomerType.setText(ctypeArr[which]);
                                    deliverGoods.khlx = intCtypeArr[which];
                                }
                            }).show();
                        }
                    });
                }
                if(careaArr!=null && careaArr.length>0) {
                    txtAddrArea.setText(currAreaName);
                    txtAddrArea.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new AlertDialog.Builder(context).setItems(careaArr, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    txtAddrArea.setText(careaArr[which]);
                                    deliverGoods.dq_id = intCareaArr[which];
                                }
                            }).show();
                        }
                    });
                }
            }
        }.execute();
    }

    /**
     * 检测参数的正确性
     * @return
     */
    public boolean checkArguments(){
        if(etCustomerName.getText().length()<=0){
            Toast.makeText(this,"请输入客户名称!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etContractor.getText().length()<=0){
            Toast.makeText(this,"请输入联系人!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etConnectity.getText().length()<=0){
            Toast.makeText(this,"请输入联系电话!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etDeliverPerson.getText().length()<=0){
            Toast.makeText(this,"请输入收货人!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etDeliverPhone.getText().length()<=0){
            Toast.makeText(this,"请输入收货电话",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etDeliverAddr.getText().length()<=0){
            Toast.makeText(this,"请输入收货地址!",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etDeliverAbbr.getText().length()<=0){
            Toast.makeText(this,"请输入收货地址简称!",Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pcustomerEdit_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
